package src.tree.level_order;

import java.util.LinkedList;
import java.util.Queue;

public class no117 {//填充每个节点的下一个右侧节点指针2

    public Node connect(Node root) {
        if (root == null) return null;
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            Node cur = null;
            Node pre = null;
            for (int i = 0; i < size; i++) {
                if(i==0){
                    pre = queue.poll();  //取出本层第一个结点
                    cur = pre;
                }else {
                    cur = queue.poll();
                    pre.next = cur;  //本层前一个node的next指向当前node
                    pre=pre.next;
                }

                if(cur.left!=null) queue.add(cur.left);
                if(cur.right!=null) queue.add(cur.right);

            }
            pre.next = null;  //本层最后一个结点 next 指向null
        }
        return root;

    }
}
